#!/usr/bin/env python
# $Id$
#
# This file is part of Phennui.
#
# Phennui is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Phennui is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Phennui.  If not, see <http://www.gnu.org/licenses/>.

import os, imp, subprocess, signal
import gobject
import fileeditor

try:
    import vte
except:
    vte = False

class Profile(gobject.GObject):
    name = None
    fname = None
    data = None
    proc = None
    state = 'Stopped'
    row = None
    shown = True
    
    def __init__(self, fname):
        gobject.GObject.__init__(self)
    
        self.name = os.path.basename(fname)[:-3]
        self.fname = fname
        self.data = fileeditor.FileEditor(fname)
      
    @staticmethod  
    def new():
        # Import phenny.
        phenny = imp.load_source('phenny', prefs.phenny_exec)
        
        # Create a new, empty config.
        name = os.path.join(prefs.configdir, 'new.py')
        i = 1
        while os.access(name, os.F_OK):
            name = os.path.join(prefs.configdir, 'new%d.py' % i )
            i += 1
        phenny.create_default_config(name)
        
        return Profile(name)
        
    def delete(self):
        try:
            os.remove(self.fname)
        except:
            pass
        self.stop()
        del self
        
    def running(self):
        return bool(self.proc and not self.proc.poll())
        
    def start(self):
        if not self.running():
            if vte: 
                self.proc = subprocess.Popen(['python', 'phennywrapper.py', prefs.phenny_exec, '-c', '"' + self.fname + '"'], 
                                             stdout = subprocess.PIPE,
                                             stderr = subprocess.PIPE, 
                                             stdin = subprocess.PIPE,
                                             preexec_fn = getattr(os, 'setsid', None))
                print >> self.proc.stdin, prefs.show_terminals and 'show' or 'hide'
            else:
                self.proc = subprocess.Popen(['python', prefs.phenny_exec, '-c', self.fname], 
                                             cwd = os.path.dirname(prefs.phenny_exec),
                                             stdout = subprocess.PIPE,
                                             stderr = subprocess.PIPE, 
                                             stdin = subprocess.PIPE,
                                             preexec_fn = getattr(os, 'setsid', None))
        self.state = 'Running'
        
    def stop(self):
        if self.running():
            if hasattr(os, 'killpg'):
                os.killpg(self.proc.pid, signal.SIGUSR1)
            else:
                self.proc.kill()
            self.proc.wait()      
        self.state = 'Stopped'     
            
    def show(self):
        print >> self.proc.stdin, 'show'
        self.shown = True
        
    def hide(self):
        print >> self.proc.stdin, 'hide'
        self.shown = False
        
    def reload(self):
        self.data = fileeditor.FileEditor(self.fname)
        

def Profiles(prefs):
    globals()['prefs'] = prefs

    # Get the dotdir, the dir where all config files are stored.
    dotdir = os.path.abspath(os.path.expanduser(prefs.configdir))
    
    # Get a list of all files and make Profiles of the valid ones.
    confs = os.listdir(dotdir).sort()
    profiles = []
    for conf in os.listdir(dotdir):
       if conf[-3:] == '.py':
            try:
                profile = Profile(os.path.join(dotdir, conf))
                if not hasattr(profile.data, 'host'):
                    raise Exception()
                profiles.append(profile)
            except:
                pass
    
    return profiles    

